package cn.e2win.biz.resolver;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import cn.e2win.base.json.vo.Pager;
import cn.e2win.biz.annotation.PageParam;


public class PageParamsResolver implements HandlerMethodArgumentResolver{

	@Override
	public Object resolveArgument(MethodParameter parameter,
			ModelAndViewContainer mavContainer, NativeWebRequest request,
			WebDataBinderFactory binderFactory) throws Exception {
		// TODO Auto-generated method stub

		PageParam pageAnno = parameter.getParameterAnnotation(PageParam.class);

		Object pageNum = request.getParameter(pageAnno.pageNum()+"");
		Object numPerPage = request.getParameter(pageAnno.numPerPage()+"");
		String orderField = request.getParameter(pageAnno.orderField()+"");
		String orderDirection = request.getParameter(pageAnno.orderDirection()+"");
		Pager pager = new Pager();
		Map<String, String> map = new HashMap<String, String>();
		
		if (pageNum != null && numPerPage != null) {
			int currentPage = Integer.valueOf(pageNum.toString());
			int pageSizeValue = Integer.valueOf(numPerPage.toString());
			pager.setPageNum(currentPage);
			pager.setNumPerPage(pageSizeValue);
		} 
		pager.setOrderField(orderField);
		pager.setOrderDirection(orderDirection);
		
		String conditionMapName = pageAnno.condition();
		Iterator<String> paramNameIter = request.getParameterNames();
		for(;paramNameIter.hasNext();){
			String paramName = paramNameIter.next();
			if(paramName.startsWith(conditionMapName + ".")){
				String value = request.getParameter(paramName);
				paramName = paramName.replace(conditionMapName + ".", "");
				map.put(paramName, value);
			}
		}

		pager.getScMap().putAll(map);
		return pager;
	}
	

	@Override
	public boolean supportsParameter(MethodParameter arg0) {
		// TODO Auto-generated method stub
		return arg0.hasParameterAnnotation(PageParam.class);
	}

}
